package cliente;

import java.awt.HeadlessException;
import static java.lang.Math.abs;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.text.ParseException;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import servidor.Alerta;
import servidor.AlertaServidor;
import servidor.ServidorInterface;
////////////////////////////////////////////////////////////////////////////////

public class GuiClient extends javax.swing.JFrame {

    private ClienteImpl clienteObj;
    private ServidorInterface h;
    DefaultListModel lmListaAlertasAct;//NOS HACEN FALTA PARA PODER MODIFICAR EL JLIST
////////////////////////////////////////////////////////////////////////////////

    public GuiClient() throws RemoteException, ParseException {
        //this.setUndecorated(true); //NOS MUESTRA LA VENTANA SIN BARRA NI BOTONES DE VENTANA
        initComponents(); //FUNCION AUTOGENERADA QUE INICIALIZA LA INTERFAZ
        misInicializaciones(); //FUNCION PROPIA QUE INICIALIZA LOS ELEMENTOS EXTERNOS A LA GUI  
    }
////////////////////////////////////////////////////////////////////////////////    

    private void misInicializaciones() throws RemoteException {
        this.setLocationRelativeTo(null); //Centramos el jframe en la pantalla
        this.clienteObj = new ClienteImpl();
        lmListaAlertasAct = new DefaultListModel();
    }
////////////////////////////////////////////////////////////////////////////////    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        grupoBotones = new javax.swing.ButtonGroup();
        jPanel1 = new javax.swing.JPanel();
        etiquetaTitulo1 = new javax.swing.JLabel();
        etiquetaTitulo2 = new javax.swing.JLabel();
        etiquetaEmpresa = new javax.swing.JLabel();
        comboBoxEmpresasAlerta = new javax.swing.JComboBox();
        etiquetaValor = new javax.swing.JLabel();
        textFieldValorAlerta = new javax.swing.JFormattedTextField();
        botonComprar = new javax.swing.JRadioButton();
        botonVender = new javax.swing.JRadioButton();
        botonCrearAlerta = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        etiTest = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        listaAlertasActivas = new javax.swing.JList();
        botonSalir = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Alertas Bursatiles del Ibex35");
        setBackground(new java.awt.Color(102, 102, 102));
        setBounds(new java.awt.Rectangle(0, 0, 0, 0));
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                ventanaActivada(evt);
            }
        });

        jPanel1.setBackground(new java.awt.Color(102, 102, 102));
        jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        etiquetaTitulo1.setFont(new java.awt.Font("Arial", 1, 16)); // NOI18N
        etiquetaTitulo1.setForeground(new java.awt.Color(204, 204, 204));
        etiquetaTitulo1.setText("Defina una nueva alerta");

        etiquetaTitulo2.setFont(new java.awt.Font("Arial", 1, 16)); // NOI18N
        etiquetaTitulo2.setForeground(new java.awt.Color(204, 204, 204));
        etiquetaTitulo2.setText("Alertas activas");

        etiquetaEmpresa.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        etiquetaEmpresa.setForeground(new java.awt.Color(204, 204, 204));
        etiquetaEmpresa.setText("Empresa:");

        comboBoxEmpresasAlerta.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        comboBoxEmpresasAlerta.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "ABERTIS SE.A", "ACCIONA", "ACS", "AMADEUS", "ARCELORMIT.", "BA.POPULAR", "BA.SABADELL", "BA.SANTANDER", "BANKIA", "BANKINTER", "BBVA", "BME", "CAIXABANK", "DIA", "EBRO FOODS", "ENAGAS", "FCC", "FERROVIAL", "GAMESA", "GAS NATURAL", "GRIFOLS CL.A", "IAG", "IBERDROLA", "INDITEX", "INDRA A", "JAZZTEL", "MAPFRE", "MEDIASET", "OHL", "R.E.C.", "REPSOL", "SACYR", "TEC.REUNIDAS", "TELEFONICA", "VISCOFAN" }));

        comboBoxEmpresasAlerta.setSelectedIndex(-1);

        etiquetaValor.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        etiquetaValor.setForeground(new java.awt.Color(204, 204, 204));
        etiquetaValor.setText("Valor:");

        textFieldValorAlerta.setBackground(new java.awt.Color(204, 204, 204));
        textFieldValorAlerta.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter()));
        textFieldValorAlerta.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N

        grupoBotones.add(botonComprar);
        botonComprar.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        botonComprar.setForeground(new java.awt.Color(204, 204, 204));
        botonComprar.setSelected(true);
        botonComprar.setText("Compra");

        grupoBotones.add(botonVender);
        botonVender.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        botonVender.setForeground(new java.awt.Color(204, 204, 204));
        botonVender.setText("Venta");

        botonCrearAlerta.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        botonCrearAlerta.setText("CREAR ALERTA");
        botonCrearAlerta.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                botonCrearAlertaMouseClicked(evt);
            }
        });

        jSeparator1.setBackground(new java.awt.Color(204, 204, 204));
        jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL);

        listaAlertasActivas.setBackground(new java.awt.Color(130, 130, 130));
        listaAlertasActivas.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        listaAlertasActivas.setForeground(new java.awt.Color(204, 204, 204));
        jScrollPane2.setViewportView(listaAlertasActivas);

        botonSalir.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        botonSalir.setText("SALIR");
        botonSalir.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                botonSalirMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(etiquetaTitulo1)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                            .addComponent(etiquetaEmpresa)
                            .addGap(21, 21, 21)
                            .addComponent(comboBoxEmpresasAlerta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(etiTest, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(botonComprar)
                                .addGap(18, 18, 18)
                                .addComponent(botonVender))))
                    .addComponent(botonCrearAlerta, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(etiquetaValor)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(textFieldValorAlerta, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(33, 33, 33)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 286, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(etiquetaTitulo2)
                        .addGap(0, 175, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(botonSalir)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(etiquetaTitulo1)
                        .addGap(28, 28, 28)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(etiquetaEmpresa)
                            .addComponent(comboBoxEmpresasAlerta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(48, 48, 48)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(etiquetaValor)
                            .addComponent(textFieldValorAlerta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(etiquetaTitulo2)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(172, 172, 172)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(botonComprar)
                                    .addComponent(botonVender))
                                .addGap(37, 37, 37)
                                .addComponent(botonCrearAlerta, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(etiTest)
                                .addGap(96, 96, 96))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 266, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(botonSalir)
                                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 325, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 346, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
////////////////////////////////////////////////////////////////////////////////
    private void botonCrearAlertaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botonCrearAlertaMouseClicked
        //ESTE METOD SE ENCARGA DE:
        //RECOGER LOS VALORES DE LA INTERFAZ,
        //CREAR UNA ALERTA EN EL VECTOR DE ALERTAS DEL CLIENTE, 
        //REALIZAR REGISTERFORCALLBACK EN EL SERVIDOR PARA EL CLIENTE 
        //ACTUALIZAR LOS VALORES DE LA INTERFAZ, RESETEANDO LOS ELEMENTOS USADOS
        //Y MOSTRANDO LAS ALERTAS ACTIVAS EN EL MOMENTO.
        try {

            if ((comboBoxEmpresasAlerta.getSelectedIndex() >= 0) && (textFieldValorAlerta.getText().length() > 0)) {
                
                //RECOGEMOS LOS VALORES DE LA ALERTA DE LA GUI
                String nombreEmpresa = (String) comboBoxEmpresasAlerta.getSelectedItem();
                float valorAlerta = Float.valueOf(String.valueOf(textFieldValorAlerta.getValue()));
                boolean comprar = botonComprar.isSelected();

                //RESETEAMOS LOS ELEMENTOS GRAFICOS DE LA GUI UTILIZADOS
                comboBoxEmpresasAlerta.setSelectedIndex(-1);
                textFieldValorAlerta.setText("");
                botonComprar.setSelected(true);

                //CONTEMPLAMOS EL CASO DE COMPRAR: VALOR DE COMPRA SERÁ NEGATIVO
                if (valorAlerta > 0 && comprar) {
                    valorAlerta = -valorAlerta;
                }

                //AÑADIMOS LA ALERTA EN EL VECTOR DE ALERTAS DEL CLIENTE
                Alerta alerta = new Alerta(nombreEmpresa, valorAlerta);
                this.clienteObj.añandirAlerta(alerta);

                //REGISTRAMOS LA ALERTA EN EL SERVIDOR
                this.h.registerForCallback(new AlertaServidor(this.clienteObj, alerta));
                System.out.println("Registered for callback: " + nombreEmpresa + " " + valorAlerta);

                //AÑADIMOS LA ALERTA AL JLIST DE ALERTAS ACTUALIZANDO EL MODELLIST DE DICHA JLIST.
                if (comprar) {
                    lmListaAlertasAct.addElement(botonComprar.getText() + "\t " + nombreEmpresa + " " + abs(valorAlerta));
                } else {
                    lmListaAlertasAct.addElement(botonVender.getText() + "\t " + nombreEmpresa + " " + abs(valorAlerta));
                }

                listaAlertasActivas.setModel(lmListaAlertasAct);
            }
        } catch (RemoteException ex) {
            System.out.println("Exception in Client: " + ex);
            Logger.getLogger(GuiClient.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(null, ex, "ERROR: Conexion con el servidor interrumpida", JOptionPane.ERROR_MESSAGE);
            System.exit(1);
        }
    }//GEN-LAST:event_botonCrearAlertaMouseClicked
////////////////////////////////////////////////////////////////////////////////

    private void botonSalirMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botonSalirMouseClicked
        //ESTE METODO SE ENCAGA DE HACER EL UNREGISTERFORCALLBACK DEL CLIENTE
        //EN EL SERVIDOR. PARA QUE NO HAYA PROBLEMAS DE CONSISTENCIA DE DATOS
        //Y SE LIBERE EN EL SERVIDOR LA INFORMACION RELATIVA A LAS ALERTAS QUE 
        //QUEDEN PENDIENTES.
        
        try {
            //HACEMOS EL UNREGISTER PARA ESTE CLIENTE.
            //SE EMPLEA PARA ELLO UNA ALERTASERVIDOR AUXILIAR, CON NINGUN VALOR.
            this.h.unregisterForCallback(new AlertaServidor(this.clienteObj, new Alerta("", 0)));
            System.exit(0);
        } catch (RemoteException ex) {
            JOptionPane.showMessageDialog(null, ex, "ERROR: Conexion con el servidor interrumpida", JOptionPane.ERROR_MESSAGE);
            Logger.getLogger(GuiClient.class.getName()).log(Level.SEVERE, null, ex);
            System.exit(1);
        }
    }//GEN-LAST:event_botonSalirMouseClicked
////////////////////////////////////////////////////////////////////////////////
    private void ventanaActivada(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_ventanaActivada
         //ACTUALIZA LA JLIST DE ALERTAS DE LA INTERFAZ, CADA VEZ QUE SE ACTIVA LA VENTANA
        Vector vAlertas = this.clienteObj.getvAlertas();

        lmListaAlertasAct = new DefaultListModel();

        for (int i = 0; i < vAlertas.size(); i++) {
            Alerta aAux = (Alerta) vAlertas.get(i);
            if (aAux.getPrecio() < 0) {
                lmListaAlertasAct.addElement("COMPRA \t " + aAux.imprimir());
            } else {
                lmListaAlertasAct.addElement("VENTA \t " + aAux.imprimir());
            }
        }
        //ACTUALIZAMOS EL JLIST CON LOS VALORES CORRECTOS
        listaAlertasActivas.setModel(lmListaAlertasAct);
    }//GEN-LAST:event_ventanaActivada
////////////////////////////////////////////////////////////////////////////////

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(GuiClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {

                try {
                    GuiClient gui = new GuiClient();
                    gui.setVisible(true);

                    String registryURL = "rmi://localhost:1235/alertasBursatiles";

                    gui.h = (ServidorInterface) Naming.lookup(registryURL);
                    JOptionPane.showMessageDialog(null, gui.h.sayConnected(), "INFO Cliente: Lookup completed", JOptionPane.INFORMATION_MESSAGE);

                } // end try
                catch (HeadlessException | MalformedURLException | NotBoundException | RemoteException | ParseException e) {
                    System.out.println("Exception in Client: " + e);
                    Logger.getLogger(GuiClient.class.getName()).log(Level.SEVERE, null, e);
                    JOptionPane.showMessageDialog(null, e, "ERROR EN EL CLIENTE", JOptionPane.ERROR_MESSAGE);
                    System.exit(1);
                }
            }//end run
        });
    }
////////////////////////////////////////////////////////////////////////////////
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JRadioButton botonComprar;
    private javax.swing.JButton botonCrearAlerta;
    private javax.swing.JButton botonSalir;
    private javax.swing.JRadioButton botonVender;
    private javax.swing.JComboBox comboBoxEmpresasAlerta;
    private javax.swing.JLabel etiTest;
    private javax.swing.JLabel etiquetaEmpresa;
    private javax.swing.JLabel etiquetaTitulo1;
    private javax.swing.JLabel etiquetaTitulo2;
    private javax.swing.JLabel etiquetaValor;
    private javax.swing.ButtonGroup grupoBotones;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JList listaAlertasActivas;
    private javax.swing.JFormattedTextField textFieldValorAlerta;
    // End of variables declaration//GEN-END:variables
}
